package com.dongdong.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.dongdong.result.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FileuploadController {

    @PostMapping("upload")
    public Result upload(@RequestBody MultipartFile img){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String start = "https://";
        String end = "oss-cn-beijing.aliyuncs.com";
        String endpoint = start+end;

        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        //EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
//        String accessKey="LTAI5tFL4t2EvxhwAkD7NX63";
//        String secret="S45IaLPY3GI8sRuxVUAWbantVHA34u";

        String accessKey="LTAI5tBWZ11rj3kXLisgiS8B";
        String secret="5KAYyC3PIR1H0PzMAIuDliQvfRHo9w";

        // 填写Bucket名称，例如examplebucket。
        String bucketName = "2202pyt";
//        String bucketName = "scw2306";
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
//        String objectName = "exampledir/exampleobject.txt";
 //获取前端上传的文件名
        // 122..555.55.55.png
        String fileName = img.getOriginalFilename();
        String objectName = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/" + UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey,secret);

        try {
            InputStream inputStream = img.getInputStream();
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String url = start+bucketName+"."+end+"/"+objectName;
        return Result.OK().setData(url);
    }





}
